from flask import Flask, render_template, request, redirect, url_for
import statistics

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/calculate', methods=['POST'])
def calculate():
    class_averages = []
    
    for i in range(1, 13):
        scores_str = request.form.get(f'class_{i}', '')
        if scores_str.strip():
            try:
                scores = [float(score.strip()) for score in scores_str.split(',') if score.strip()]
                if scores:
                    avg = round(statistics.mean(scores), 2)
                    class_averages.append({
                        'class_name': f'班级 {i}',
                        'average': avg,
                        'student_count': len(scores)
                    })
                else:
                    class_averages.append({
                        'class_name': f'班级 {i}',
                        'average': 0,
                        'student_count': 0
                    })
            except ValueError:
                class_averages.append({
                    'class_name': f'班级 {i}',
                    'average': '输入格式错误',
                    'student_count': 0
                })
        else:
            class_averages.append({
                'class_name': f'班级 {i}',
                'average': 0,
                'student_count': 0
            })
    
    return render_template('result.html', class_averages=class_averages)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
